use clap::Parser;
use colored::*;
use console::Term;
use rand::prelude::*;
use rand::rng;
use std::{
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    thread,
    time::{Duration, Instant},
};

mod activities;
mod config;
mod display;
mod generators;
mod types;
use types::{Complexity, DevelopmentType, JargonLevel};

/// 当利益相关者经过时生成令人印象深刻的终端输出的CLI工具
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// 要模拟的开发活动类型
    #[arg(short, long, value_enum, default_value_t = DevelopmentType::Backend)]
    dev_type: DevelopmentType,

    /// 输出中的技术术语级别
    #[arg(short, long, value_enum, default_value_t = JargonLevel::Medium)]
    jargon: JargonLevel,

    /// 输出看起来的繁忙和复杂程度
    #[arg(short, long, value_enum, default_value_t = Complexity::Medium)]
    complexity: Complexity,

    /// 运行时长（0=持续运行直到中断）
    #[arg(short = 'T', long, default_value_t = 0)]
    duration: u64,

    /// 显示关键系统警报或问题
    #[arg(short, long, default_value_t = false)]
    alerts: bool,

    /// 模拟特定项目
    #[arg(short, long, default_value = "分布式集群")]
    project: String,

    /// 使用较少颜色输出
    #[arg(long, default_value_t = false)]
    minimal: bool,

    /// 显示团队协作活动
    #[arg(short, long, default_value_t = false)]
    team: bool,

    /// 模拟特定框架使用
    #[arg(short = 'F', long, default_value = "")]
    framework: String,
}

fn main() {
    let args = Args::parse();

    let config = config::SessionConfig {
        dev_type: args.dev_type,
        jargon_level: args.jargon,
        complexity: args.complexity,
        alerts_enabled: args.alerts,
        project_name: args.project,
        minimal_output: args.minimal,
        team_activity: args.team,
        framework: args.framework,
    };

    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();

    // 设置Ctrl-C信号处理程序
    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
    })
        .expect("设置Ctrl-C处理程序时出错");

    let term = Term::stdout();
    let _ = term.clear_screen();

    // 显示初始"系统启动"序列营造氛围
    display::display_boot_sequence(&config);

    let start_time = Instant::now();
    let target_duration = if args.duration > 0 {
        Some(Duration::from_secs(args.duration))
    } else {
        None
    };

    while running.load(Ordering::SeqCst) {
        if let Some(duration) = target_duration {
            if start_time.elapsed() >= duration {
                break;
            }
        }

        // 根据复杂度确定同时显示的活动数量
        let activities_count = match config.complexity {
            Complexity::Low => 1,
            Complexity::Medium => 2,
            Complexity::High => 3,
            Complexity::Extreme => 4,
        };

        // 随机选择并执行活动
        let mut activities: Vec<fn(&config::SessionConfig)> = vec![
            activities::run_code_analysis,
            activities::run_performance_metrics,
            activities::run_system_monitoring,
            activities::run_data_processing,
            activities::run_network_activity,
        ];
        activities.shuffle(&mut rng());

        for activity in activities.iter().take(activities_count) {
            activity(&config);

            // 活动之间的随机短暂停顿
            let pause_time = rng().random_range(100..500);
            thread::sleep(Duration::from_millis(pause_time));

            // 检查是否需要退出
            if !running.load(Ordering::SeqCst)
                || (target_duration.is_some() && start_time.elapsed() >= target_duration.unwrap())
            {
                break;
            }
        }

        // 随机显示警报
        if config.alerts_enabled && rng().random_ratio(1, 10) {
            display::display_random_alert(&config);
        }

        // 随机显示团队活动
        if config.team_activity && rng().random_ratio(1, 5) {
            display::display_team_activity(&config);
        }
    }

    let _ = term.clear_screen();
    println!("{}", "会话已终止。".bright_green());
}
